/**
 * 
 */
package com.testing.string.related;

import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * @author Jason
 *
 */
public class CharsetPOC {
	StringBuilder sb=new StringBuilder(1000);
	static String LINE_SEPERATOR=System.getProperty("line.separator");
	
	/**
	 * method to return the number of Charset(s) supported
	 * @return
	 */
	public String getCharsetsAvailable() {
		Map<String, Charset> aCharsets=Charset.availableCharsets();
		
		if (aCharsets!=null && !aCharsets.isEmpty()) {
			Set<Entry<String, Charset>> aEntries=aCharsets.entrySet();
			
			this.sb.delete(0, this.sb.length());
			for (Entry<String, Charset> aEntry:aEntries) {
				this.sb.append("Key:: ").append(aEntry.getKey()).
					append("; Value:: ").append(aEntry.getValue()).
					append(LINE_SEPERATOR);
			}
		}	// end if charset(s) not null
		return this.sb.toString();
	}
	
	/**
	 * simple method to get the byte[] for the given charset
	 * @param pCharset
	 * @param pString
	 * @return
	 */
	public byte[] getBytesInCharset(Charset pCharset, final String pString) {
		byte[] aBytes=null;
		
		if (pString!=null && !pString.isEmpty() && pCharset!=null) {
			/*int aOriIdx=-1;
			String aTarString=null;
			
			ByteBuffer aBBuffer=pCharset.newEncoder().
				encode(CharBuffer.wrap(pString));
			
			aOriIdx=aBBuffer.position();
			aTarString=pCharset.newDecoder().decode(CharBuffer.wrap(pString));*/
			aBytes=pString.getBytes(pCharset);
		}
		return aBytes;
	}
	
	/**
	 * simple method to return the the String by the given Charset + the given
	 * byte[]
	 * @param pCharset
	 * @param pBytes
	 * @return
	 */
	public String getStringFromCharset(Charset pCharset, final byte[] pBytes) {
		String aString=null;
		
		if (pBytes!=null && pCharset!=null) {
			try {
				aString=new String(pBytes, pCharset.name());
				
			} catch (Exception e) {
				throw new RuntimeException("[CharsetPOC][getStringFromCharset]", e);
			}
		}
		return aString;
	}
	
}
